<?php

namespace app\api\model\wine;

use app\api\model\user\Grade;
use app\common\model\BaseModel;
use app\common\model\Order;

class Dermember extends BaseModel
{
    protected $autoWriteTimestamp = true;
    public function user()
    {
        return $this->hasOne(User::class, 'user_id', 'user_id')
            ->bind(['mobile', 'nick_name']);
    }
    //添加
    public function add($param)
    {
        $data = [
            'store_id' => getStoreId(),
            'pid' => $param['pid'],
            'user_id' => $param['user_id'],
            'idCard' => $param['idCard'] ?? ''
        ];
        try {
            if (isset($param['id'])) {
                return $this->where(['id' => $param['id']])->save($data);
            } else {
                //创建经销商，如果身份证相同则更新数据
                $r = $this->where(['user_id' => $param['user_id']])->findOrEmpty();
                if ($r->isEmpty()) {
                    return $this->save($data);
                }
                return false;
            }
        } catch (\Exception $exception) {
            throw new \think\Exception('添加或更新数据异常', 10006);
        }
    }
    //获取经销商信息
    public function getDerInfo($user_id)
    {
        return $this->where(['user_id' => $user_id, 'store_id' => self::$storeId])
            ->with('user')
            ->find();
    }
    //获取旗下的经销商
    public function getSonDerData($pid, $weight = 1)
    {
        return $this->where(['d.pid' => $pid, 'd.store_id' => self::$storeId])
            ->alias('d')
            ->leftJoin('user u', 'u.user_id = d.user_id')
            ->leftJoin('user_grade g', 'g.grade_id = u.grade_id')
            ->where('g.weight', '>=', $weight)
            ->select();
    }
    //获取旗下的数量
    public function getSonDerCount($pid, $weight = 1)
    {
        return $this->where(['d.pid' => $pid, 'd.store_id' => self::$storeId])
            ->alias('d')
            ->where('g.weight', '>=', $weight)
            ->leftJoin('user u', 'u.user_id = d.user_id')
            ->leftJoin('user_grade g', 'g.grade_id = u.grade_id')
            ->count();
    }
    //获取Pid的经销商信息
    public function getPDerData($user_id)
    {
        return $this->where(['d1.user_id' => $user_id, 'd1.store_id' => self::$storeId])
            ->alias('d1')
            ->field('d2.profit,d2.id,d2.user_id')
            ->leftJoin('dermember d2', 'd1.pid = d2.user_id')
            ->find();
    }

    //代理账户余额增加
    public function setIncProfitMoney($id, $money)
    {
        return $this->where('id', $id)
            ->inc('profit', $money)
            ->update();
    }

    // 代理账户余额获取
    public function getProfitMoney($id)
    {
        return $this->where('id', $id)
            ->lock(true)
            ->value('profit');
    }

    // 关联用户会员等级
    public function usergrade(){
        return $this->hasOne(\app\common\model\User::class,'user_id','user_id')
            ->bind(['grade_id']);
    }

    // 上一个月
    private function lastMonth(){
        $i = 1;
        return date( 'Y-m', strtotime( 'last day of -'.$i.' months' ) ).'-01';
    }

    // 本月
    private function theMonth(){
        return date('Y-m-01');
    }

    // 商户月现金流水统计
    private function merchStat(int $user_id)
    {
        $pay_price_sum = $this->alias('d')
            ->where(['d.is_delete' => 0, 'd.store_id' => self::$storeId, 'o.pay_status' => 20,'d.user_id'=>$user_id])
            ->leftJoin('order o', "o.user_id = d.user_id")
            ->whereBetweenTime('o.create_time',$this->lastMonth(),$this->theMonth())
            ->sum('pay_price');
        $pay_price_count = $this->alias('d')
            ->where(['d.is_delete' => 0, 'd.store_id' => self::$storeId, 'o.pay_status' => 20,'d.user_id'=>$user_id])
            ->leftJoin('order o', 'o.user_id = d.user_id')
            ->whereBetweenTime('o.create_time',$this->lastMonth(),$this->theMonth())
            ->count('pay_price');
        return [
            'sum' => $pay_price_sum,
            'count' => $pay_price_count
        ];
    }

    // 关联商户名称
    public function merchname(){
        return $this->hasOne(User::class, 'user_id', 'user_id')
            ->bind(['nick_name']);
    }

    // 商户现金流水月明细
    public function merchMonth(){
        $arr = $this->where(['is_delete'=>0,'store_id'=>getStoreId()])
            ->with('merchname')
            ->order('create_time','desc')
            ->field('user_id,create_time')
            ->paginate(15);
        $data = $arr->toArray() ['data'];
        foreach ($data as $i =>$item){
            $user_id = $item['user_id'];
            $dataArr = $this->merchStat($user_id);
            $data[$i]['sum'] = $dataArr['sum'];
            $data[$i]['count'] = $dataArr['count'];
        }
        $array = $arr->toArray();
        $array['data'] = $data;
        return $array;
    }

    // 经销商关联用户
    public function myuser(){
        return $this->hasOne(\app\common\model\User::class, 'user_id', 'user_id')
            ->with('grade')
            ->bind(['mobile', 'nick_name','grade']);
    }

    // 我的经销商列表
    public function myder(string $keyword)
    {
        if(is_numeric($keyword) && preg_match("/^1[34578]\d{9}$/", $keyword)) {
            $where[] = ['u.mobile','=',$keyword];
        }else{
            $where[] = ['u.nick_name','like',"%{$keyword}%"];
        }
        return $this->where(['d.is_delete' => 0, 'd.store_id' => getStoreId()])
            ->alias('d')
            ->where($where)
            ->with('myuser')
            ->order('d.create_time','desc')
            ->leftJoin('user u','d.user_id = u.user_id')
            ->field('d.user_id,d.pcount,d.total_expend_money,d.award_money')
            ->paginate(15);
    }
}
